import React, { FC, useEffect } from 'react';
import { Modal, Form, InputNumber, Input, Select } from 'antd';
import { OperationMemberItem } from '@/services/operation/member';

interface LoanProps {
  open: boolean;
  operationMemberItem: Partial<OperationMemberItem> | undefined;
  onSubmit: (values: OperationMemberItem) => void;
  onCancel: () => void;
}

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const MemberOpForm: FC<LoanProps> = (props) => {
  const [form] = Form.useForm();
  const { open, operationMemberItem, onCancel, onSubmit } = props;

  useEffect(() => {
    if (form && !open) {
      form.resetFields();
    }
  }, []);

  useEffect(() => {
    if (operationMemberItem) {
      form.setFieldsValue({
        ...operationMemberItem
      });
    }
  }, [props.operationMemberItem]);

  const handleOpSubmit = () => {
    if (!form) return;
    form.submit();
  };

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit({ ...values} as OperationMemberItem);
    }
  };

  const modalFooter = { okText: '保存', onOk: handleOpSubmit, onCancel };

  const renderContent = () => {
    return (
      <>
        <Form.Item
          label="手机号"
          name="mobile"
        >
          <Input readOnly/>
        </Form.Item>
        <Form.Item
          label="姓氏"
          name="firstName"
        >
          <Input placeholder="请输入姓氏" readOnly/>
        </Form.Item>
        <Form.Item
          label="当前余额"
          name="balance"
        >
          <InputNumber style={{ width: '100%' }} readOnly/>
        </Form.Item>
        <Form.Item
          label={`${
            operationMemberItem?.opType === 'IN' ? '充值金额' : '消费金额'
          }`}
          name="opAmount"
          rules={[{ required: true, message: '请输入金额' }]}
        >
          <InputNumber
            style={{ width: '100%' }}
            step={1000}
            formatter={(value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            placeholder="请输入金额"
          />
        </Form.Item>
        <Form.Item label="备注" name="remark">
          <Input.TextArea rows={4} placeholder="请输入备注" />
        </Form.Item>      
        <Form.Item hidden={true} name="id">
          <Input hidden={true} />
        </Form.Item>
        <Form.Item hidden={true} name="opType">
          <Input hidden={true} />
        </Form.Item>
      </>
    );
  };

  return (
    <Modal
      title={`${
        operationMemberItem?.opType === 'IN' ? '会员充值' : '会员消费'
      }`}
      width={640}
      destroyOnClose
      open={open}
      {...modalFooter}
    >
      <Form {...formLayout} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default MemberOpForm;